#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

//./client 服务器的IP 服务端的端口号
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cout<< argv[0] << "serve-ip serve-port" <<std::endl;
        exit(0);
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cout<< "socket creat error" <<std::endl;
        exit(1);
    }
    while(1)
    {
        //服务端先收消息再发消息，客户端先发消息再收消息
        std::string line;
        std::cout<< "Please Enter" <<std::endl;
        std::getline(std::cin, line);

        struct sockaddr_in sever;
        memset(&sever, 0, sizeof(sever));
        sever.sin_family = AF_INET;
        sever.sin_port = htons(port);
        sever.sin_addr.s_addr = inet_addr(ip.c_str());
        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr*)&sever, sizeof(sever));
        if(n > 0)
        {
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            char buf[1024];
            int num = recvfrom(sockfd, buf, sizeof(buf)-1, 0, (struct sockaddr*)&tmp, &len);
            if(num > 0)
            {
                buf[num] = 0;
                std::cout << buf <<std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    close(sockfd);

    return 0;
}